
import fetch from "node-fetch";
import plugin from '../../../lib/plugins/plugin.js'
import fs from 'fs'
const apis = [
 'http://newbotai.cn/API/czmt.php',
]

let useapi = apis
let cd = false
export class xy_sjv extends plugin {
  constructor() {
    super({
      name: '云溪院随机小姐姐',
      dsc: '没啥好看的',
      event: 'message',
      priority: 100,
      rule: [{
        reg: '^#?随机小姐姐|sjxjj|xjj$',
        fnc: 'sjxjj'
      }]
    })

  }
  
  async sjxjj(e) {
    if (cd) return e.reply('我知道你很急，但你先别急')
    cd = true
    try {
    let video = await getVideo(e)
    if (!(/http/.test(video))) video = 'https:' + video 
    logger.warn('视频链接：' + video)
    let res = await fetch(video)
    res = await res.arrayBuffer()
    fs.writeFileSync(`${process.cwd()}/plugins/xiaoyue-plugin/resources/xyplus/xyxjj.mp4`, Buffer.from(res), "binary")
      if (!global.segment) {
        let OICQ = await import("oicq")
        global.segment = OICQ.segment
      }
    let reply = await e.reply(segment.video(`${process.cwd()}/plugins/xiaoyue-plugin/resources/xyplus/xyxjj.mp4`))
    if (!reply) e.reply('发送视频失败，请重试')
    } catch(err) {
      logger.warn(err)
      e.reply('接口失效')
    }
    cd = false
  }
}

async function getVideo(e) {
  let res = await response()
  let i = 0
  while (!res && i < apis.length) {
    res = await response()
    i++
  }
  if (i > apis.length) return e.reply('接口失效')
  let video = res.url || res.mp4 || res
  return video
}


async function response() {
  let num = Math.round(Math.random() * (useapi.length - 1))
  logger.warn(`尝试请求接口:${useapi[num]}`)
  try{
  let res = await fetch(useapi[num])
  if (res.headers.get('content-type').includes('json')) {
     res = await res.json()
     return res
  }
  return useapi[num]
 } catch(err) {
    logger.warn(useapi[num] + '，接口失效')
    useapi.splice(num, 1)
    return false
 }
}
